<?php
namespace Admin\ Controller;
use\ Admin\ Model\ ActivityModel;
use\ Admin\ Model\ BookModel;
include "./Common/CheckAdmin.php";
//活动类
final class ActivityController {
	//显示用户列表
	public function showActivity() {
		//实例化UserModel对象
		$activityModelObj = new ActivityModel();

		//以下为分页的代码
		//每页显示条数
		$pagesize = $GLOBALS[ 'config' ][ 'pagesize' ];
		//获取当前页面
		$page = isset( $_GET[ 'page' ] ) ? $_GET[ 'page' ] : 1;
		//获取开始行号(每一页的第一行应该是这一页页数-1然后乘以每页大小)
		$startrows = ( $page - 1 ) * $pagesize;
		//获取总记录数,数据库rowcount
		$rows = $activityModelObj->rowCount();
		//计算总页数（所有行数，除以每页数量就应该是总行数。但是必须上取整，因为最后一页可能不足$pagesize的数量）
		$pages = ceil( $rows / $pagesize );
		//开始页码
		//结束页码
		$start = $page - 5;
		$end = $page + 4;
		if ( $page <= 6 ) {
			$start = 1;
			$end = 10;
		}
		if ( $page >= $pages - 4 ) {
			$start = $pages - 9;
			$end = $pages;
		}
		if ( $pages < 10 ) {
			$start = 1;
			$end = $pages;
		}

		//分页获取记录
		$arrs = $activityModelObj->fetchByPages( $startrows, $pagesize );
		//引入视图文件
		include VIEW_PATH . "showActivity.html";
	}

	//加载编辑or详情视图
	public function editActivityView() {
		$id = $_GET[ 'id' ];
		$activityModelObj = new ActivityModel();
		$arr = $activityModelObj->fetchOne( $id );
		include VIEW_PATH . "editActivity.html";
	}

	//加载新增活动视图
	public function addActivityView() {
		include VIEW_PATH . "addActivity.html";
	}

	//新增活动
	public function addActivity() {
		/*获取一个活动的基本信息：活动名、地点、合作方、受益方、开始时间、（结束时间由点击结束时系统生成）、（捐书数最后生成）、预计花费金额、活动类型（0对外、1内部）*/
		$name = $_POST[ 'activity_name' ];
		$place = $_POST[ 'activity_place' ];
		$a = $_POST[ 'activity_partner_a' ];
		$b = $_POST[ 'activity_partner_b' ];
		$c = $_POST[ 'activity_partner_c' ];
		$re = $_POST[ 'activity_recipient' ];
		$begin = $_POST[ 'activity_begin' ];
		$money = $_POST[ 'activity_money' ];
		$type = $_POST[ 'activity_type' ];
		$pic_arr = $_POST[ 'pic' ];
		$activityModelObj = new ActivityModel();

		$id = $activityModelObj->addActivity( $name, $place, $a, $b, $c, $re, $begin, $money, $type );
		//接收到这一条的ID之后，就开始向调用方法数据库
		$flag = $this->addImg( $pic_arr, $id );

		if ( $id != 0 ) { //成功插入一条
			//$id = $activityModelObj -> pdo -> lastInsertId();//获取最后一条id，在Model里进行本操作，要记得也要在MyPDO里实现该接口
			echo $id;
		} else {
			echo 0;
		}

		//如果金额不为空也不为0，那就要向money_whereabouts插入
		if ( $money != null && $money != 0 ) {
			$a = $activityModelObj->addmoney( $id, $money );
			//$a这里接受返回的受影响行数
			if ( $a != 1 ) {
				echo "$.notify({
    		// options
    		message: '插入资金去向失败<br>请联系系统管理员（程序员）',
    		//url: '?c=User&a=showUser',
    		//target: '_self'
		  },{
    		// settings
    		type: 'danger',
    		delay: 5000,
    		placement: {
    		from: 'top',
    		align: 'right'
    		}
		  });";
			}
		}
		//将基本信息插入到数据库love_activity表后，返回这个活动的ID

		//加载下一步的视图，就是对book_whereabouts的操作，这里前端可以这样实现：Ajax提交，成功后val("")，然后将这一类书的信息append到旁边“已添书籍”一栏，下面三个按钮：添加、重填、完成

		//添加就是对去向表进行插入，完成就是跳转到列表页面，同时计算总数后更新表
	}

	//加载活动添加捐赠书籍的视图
	public function addActivityBookView() {
		$activity_id = $_GET[ 'id' ];
		//加载库存书籍
		$bookModelObj = new BookModel();
		$bookArrs = $bookModelObj->fetchAll();
		include VIEW_PATH . "addActivityBook.html";
	}

	//添加某一活动的捐赠书籍
	public function addActivityBook() {
		$activity_id = $_POST[ 'id' ];
		$book_id = $_POST[ 'book_id' ];
		$book_name = $_POST[ 'book_name' ];
		$book_count = $_POST[ 'book_count' ];

		$activityModelObj = new ActivityModel();
		$row = $activityModelObj->addActivityBook( $activity_id, $book_id, $book_name, $book_count );
		if ( $row == 1 ) {
			echo 200;
		} else {
			echo 500;
		}
	}

	//完成书籍添加后，点击“完成”
	public function showActivityandBook() {
		$activity_id = $_GET[ 'id' ];
		//计算本活动的捐书总数
		$activityModelObj = new ActivityModel();
		$sum = $activityModelObj->countBook( $activity_id );
		$sum1 = $sum[ 0 ][ 'SUM(book_count)' ];
		//把捐书总数更新到activity表的字段中
		$activityModelObj->updateBookCount( $activity_id, $sum1 );

		//获取该活动的结果集
		$activityArrs = $activityModelObj->fetchOne( $activity_id );
		//获取该活动对应书籍的结果集
		$activityBookArrs = $activityModelObj->fetchActivityBook( $activity_id );

		//引入视图
		include VIEW_PATH . "showActivityandBook.html";
	}


	//编辑活动基本信息
	public function editActivity() {
		$id = $_POST[ 'id' ];
		$name = $_POST[ 'activity_name' ];
		$place = $_POST[ 'activity_place' ];
		$a = $_POST[ 'activity_partner_a' ];
		$b = $_POST[ 'activity_partner_b' ];
		$c = $_POST[ 'activity_partner_c' ];
		$re = $_POST[ 'activity_recipient' ];
		$begin = $_POST[ 'activity_begin' ];
		$end = $_POST[ 'activity_end' ];
		$book = $_POST[ 'activity_book' ];
		$money = $_POST[ 'activity_money' ];
		$status = $_POST[ 'activity_status' ];
		$type = $_POST[ 'activity_type' ];

		$activityModelObj = new ActivityModel();

		//如果活动已结束，不能做任何更改
		$res = $activityModelObj->getStatus( $id );
		if ( $res[ 'activity_status' ] == 2 ) {
			echo 501;
			exit();
		}
		//编辑money_whereabouts
		$activityModelObj->editmoney( $id, $money );

		$row = $activityModelObj->editActivity( $id, $name, $place, $a, $b, $c, $re, $begin, $end, $book, $money, $status, $type );

		if ( $row == 1 ) {
			echo 200;
		} else {
			echo 500;
		}
	}

	//删除某活动的某捐赠书籍
	public function delActivityBook() {
		$id = $_GET[ 'id' ];
		$aid = $_GET[ 'aid' ];
		$activityModelObj = new ActivityModel();
		$row = $activityModelObj->delActivityBook( $id );
		if ( $row == 1 ) {
			$mes = [
				"code" => 200,
				"msg" => "删除成功<br>页面即将自动跳转",
				"url" => "?c=Activity&a=showActivityandBook&id=$aid"
			];
			$json = json_encode( $mes );
			echo $json;
		}
	}

	//计算书籍的最大可捐量
	public function getCapacity() {
		$id = $_POST[ 'id' ];
		//计算书籍在系统中的总量,库存量+已捐量
		$activityModelObj = new ActivityModel();
		$sum1 = $activityModelObj->getBookSum( $id );
		//echo $sum['sum'];
		//计算书籍在去向表中的总数
		$sum2 = $activityModelObj->getBookOut( $id );
		$sum = $sum1[ 'sum' ] - $sum2[ 0 ][ 'SUM(book_count)' ];
		echo $sum;
	}

	//删除
	public function delActivity() {
		$id = $_GET[ 'id' ];
		$activityModelObj = new ActivityModel();
		$row = $activityModelObj->delActivity( $id );
		if ( $row == 1 ) {
			$mes = [
				"code" => 200,
				"msg" => "删除成功<br>",
				//"url"=>"?c=Activity&a=showActivity"
			];
			$json = json_encode( $mes );
			echo $json;
		}
	}

	//设为已开始
	public function setOn() {
		$id = $_GET[ 'id' ];
		$activityModelObj = new ActivityModel();
		$row = $activityModelObj->setOn( $id );
		if ( $row == 1 ) {
			$mes = [
				"code" => 200,
				"msg" => "成功设为已开始<br>",
				//"url"=>"?c=User&a=showUser"
			];
			$json = json_encode( $mes );
			echo $json;
		}
	}

	//设为已结束
	public function setOff() {
		$id = $_GET[ 'id' ];
		$activityModelObj = new ActivityModel();
		//将本活动捐赠的书籍出库
		//获取该活动对应书籍的结果集
		$activityBookArrs = $activityModelObj->fetchActivityBook( $id );
		//遍历结果集，把捐出的每一种书的数量在库存表中减去
		foreach ( $activityBookArrs as $arr ) {
			$book_id = $arr[ 'book_id' ];
			$count = $arr[ 'book_count' ];
			$activityModelObj->outBook1( $book_id, $count ); //减库存
			$activityModelObj->outBook2( $book_id, $count ); //加出量
		}
		//如果金额不为空也不为0，那就要在common表中余额减去
		//得到金额
		$res = $activityModelObj->getMoney( $id );
		$money = $res[ 'activity_money' ];
		if ( $money != null && $money != 0 ) {
			$activityModelObj->outMoney( $money );
		}
		$row = $activityModelObj->setOff( $id );
		if ( $row == 1 ) {
			$mes = [
				"code" => 200,
				"msg" => "成功设为已结束<br>",
				//"url"=>"?c=User&a=showUser"
			];
			$json = json_encode( $mes );
			echo $json;
		}
	}

	//设为其他
	public function setOther() {
		$id = $_GET[ 'id' ];
		$activityModelObj = new ActivityModel();
		$row = $activityModelObj->setOther( $id );
		if ( $row == 1 ) {
			$mes = [
				"code" => 200,
				"msg" => "成功设为其他<br>",
				//"url"=>"?c=User&a=showUser"
			];
			$json = json_encode( $mes );
			echo $json;
		}
	}

	//本方法为在数据库中添加图片记录的方法，！！！不是图片上传方法
	public function addImg( $pic_arr, $activity_id ) {
		$activityModelObj = new ActivityModel();
		foreach ( $pic_arr as $pic ) {
			$activityModelObj->addImg( $pic, $activity_id );
			if ( $flag != 1 ) {
				return 0;
			}
		}
	}

	//plupload上传活动图片并且返回文件路径加名字的方法，！！！这里才是图片上传方法
	public function upImg() {
		$typeArr = array( "jpg", "png", "gif", "jpeg" ); //允许上传文件格式  
		$path = "./Upload/Activity/img/"; //上传路径  
		$name = $_FILES[ 'file' ][ 'name' ];
		$size = $_FILES[ 'file' ][ 'size' ];
		$name_tmp = $_FILES[ 'file' ][ 'tmp_name' ];
		if ( empty( $name ) ) {
			echo json_encode( array( "error" => "您还未选择图片" ) );
			exit;
		}
		$type = strtolower( substr( strrchr( $name, '.' ), 1 ) ); //获取文件类型  

		if ( !in_array( $type, $typeArr ) ) {
			echo json_encode( array( "error" => "请上传jpg,png或gif类型的图片！" ) );
			exit;
		}
		if ( $size > ( 1024 * 1024 * 10 ) ) {
			echo json_encode( array( "error" => "图片大小已超过10MB！" ) );
			exit;
		}

		$pic_name = date( YmdHi ) . rand( 10000, 99999 ) . "." . $type; //图片名称  
		$pic_url = $path . $pic_name; //上传后图片路径+名称  
		if ( move_uploaded_file( $name_tmp, $pic_url ) ) { //临时文件转移到目标文件夹  
			echo json_encode( array( "error" => "0", "pic" => $pic_url, "name" => $pic_name ) );
		} else {
			echo json_encode( array( "error" => "上传有误，清检查服务器配置！" ) );
		}

	}
}
?>